import { loginApi, logoutApi } from '@/api/auth'
import { getToken, setToken } from '@/hooks/network/useCookie'
import { LoginParams } from '@/types/request'
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken() || ''
  }),
  actions: {
    commitToken(info: string) {
      this.token = info
    },
    async login(params: LoginParams) {
      const data = await loginApi(params)
      if (data.code === 0) {
        this.commitToken(data.data.token)
        setToken(data.data.token)
      } else {
        this.commitToken('')
        setToken('')
      }
    },
    async logout() {
      const data = await logoutApi()
      if (data.code === 0) {
        this.commitToken('')
        setToken('')
      }
    }
  }
})
